package com.roast.pages;

import com.roast.domain.*;
import com.roast.services.my.MyServicesFacade;
import com.roast.services.messges.GetSystemMessageFacade;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionAttribute;
import org.apache.tapestry5.ioc.annotations.InjectService;

public class Edit {

    @InjectService("MyServicesFacade")
    MyServicesFacade myServices;

    @InjectService("GetSystemMessageFacade")
    GetSystemMessageFacade getSystemMessage;

    @SessionAttribute
    boolean loginSA;

    @SessionAttribute
    UserData userSA;

    @Property
    String email;

    @Property
    String oldNickname;

    @Property
    String newNickname;

    @Property
    String newPassword;

    @Property
    String systemMessage = " ";

    @OnEvent(value = "submit", component = "edituser")
    Object onFormSubmit() {
        UserData user = new UserData();

        user.setUserID(userSA.getUserID());
        user.setEmail(userSA.getEmail());
        user.setNickname(newNickname);
        user.setPassword(newPassword);

        int signal = myServices.edit(user);
        if (signal == 10400) {
            userSA.setNickname(newNickname);
            userSA.setPassword(newPassword);
        }
        systemMessage = getSystemMessage.edit(signal);
        return null;
    }

    Object onActivate(String data) {
        if (!loginSA) {
            return Index.class;
        } else {
            String[] dataSplit = data.split("#");

            email = dataSplit[0];
            oldNickname = dataSplit[1];
            systemMessage = dataSplit[2];

            return null;
        }
    }

    String onPassivate() {
        String data = "";

        data += userSA.getEmail();
        data += "#";

        data += userSA.getNickname();
        data += "#";

        data += systemMessage;

        return data;
    }
}
